package ran.quzitech.rnutils;

import java.math.BigInteger;

/**
 * Created by ran on 2016/6/21.
 */


public class HexString {
    public static String binaryFormat(String bin) {
        if (bin.length() < 48) {
            int de = 48 - bin.length();
            for (int i = 0; i < de; i++) {
                bin = "0" + bin;
            }
        }
        return bin;

    }

    /**
     * 将byte数组转换成相应进制字符串
     *
     * @param bytes 要转换的byte数组
     * @param radix 传进去的进制数
     * @return
     */
    public static String binary(byte[] bytes, int radix) {
        //Todo  binaryFormat 只是规格化了二进制成48的
        return binaryFormat(new BigInteger(1, bytes).toString(radix));// 这里的1代表正数
    }

    public static byte[] getMacBytes(String mac) {
        byte[] macBytes = new byte[6];
        String[] strArr = mac.split(":");

        for (int i = 0; i < strArr.length; i++) {
            int value = Integer.parseInt(strArr[i], 16);
            macBytes[i] = (byte) value;
        }
        return macBytes;
    }

    public static String getStringMac(byte[] macBytes) {
        String value = "";
        for (int i = 0; i < macBytes.length; i++) {
            String sTemp = Integer.toHexString(0xFF & macBytes[i]);
            value = value + sTemp + ":";
        }

        value = value.substring(0, value.lastIndexOf(":"));
        return value;
    }

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];

        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }

        return new String(hexChars);
    }

    public static byte[] hexToBytes(String hexRepresentation) {
        int len = hexRepresentation.length();
        byte[] data = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexRepresentation.charAt(i), 16) << 4)
                    + Character.digit(hexRepresentation.charAt(i + 1), 16));
        }

        return data;
    }
}
